package ssq.gamest.webserver;

import java.io.File; //#ifdef Java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpConnection;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.FileEntity;//#ifdef Java
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;

import ssq.utils.HTTPUtils;
import ssq.utils.LogUtils;
import ssq.utils.Utilities;

public class FileHandler extends HandlerUtils
{
    final private String index;
    final private String docRoot; //#ifdef Java
                                  
    public FileHandler(final String root, final String index) throws Exception
    {
        this.docRoot = root;//#ifdef Java
        this.index = index;
    }
    
    @Override
    public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException
    {
        List<String> l = new ArrayList<String>();
        if (parse(request, l).size() == 0)
        {
            return;
        }
        
        String path = l.get(1);
        path = path.equals("/") ? path.concat(index) : path;
        
        //##ifdef Java
        File file = new File(docRoot, path);
        
        if (!file.exists())
        {
            sendNotFound(response, file.getPath());
            LogUtils.logString(file.getPath(), "File  not found", false);
        }
        else if (!file.canRead() || file.isDirectory())
        {
            sendAccessDenied(response);
            LogUtils.logString(file.getPath(), "Cannot read file", false);
        }
        else
        {
            response.setStatusCode(HttpStatus.SC_OK);
            FileEntity body = new FileEntity(file, HTTPUtils.guessContentTypeFromName(path));
            response.setEntity(body);
        }
        //##else
        
        if (Utilities.DEBUG_ON && Utilities.LOG_ON)
        {
            HttpCoreContext coreContext = HttpCoreContext.adapt(context);
            HttpConnection conn = coreContext.getConnection(HttpConnection.class);
            LogUtils.logString(file.getPath(), conn + ": serving file", true); //#ifdef Java
        }
        //##endif
    }
}
